from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from dawn.inbox.forms import SendMessageForm
from dawn.inbox.models import Message

@login_required
def inbox(request):
    messages = request.user.received_message_set.exclude(is_deleted=1).order_by('is_read', '-post_time');
    return render_to_response('inbox/inbox.html', 
                              {'messages': messages},
                              context_instance=RequestContext(request))

@login_required
def outbox(request):
    messages = request.user.sended_message_set.exclude(is_deleted=2).order_by('-post_time');
    return render_to_response('inbox/outbox.html', 
                              {'messages': messages},
                              context_instance=RequestContext(request))

@login_required
def read_message(request, message_id):
    message = Message.objects.get(id=message_id)
    message.is_read = True
    message.save()
    return render_to_response('inbox/read_message.html',
                              {'message': message},
                              context_instance=RequestContext(request))

@login_required
def send_message(request):
    if request.method == 'POST':
        form = SendMessageForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            
            receiver_email = cleaned_data['receiver']
            receiver = User.objects.get(email=receiver_email)
            msg = Message()
            msg.sender_id = request.user.id
            msg.receiver = receiver
            msg.title = cleaned_data['title']
            msg.content = cleaned_data['content']
            msg.save()
            return HttpResponseRedirect('/inbox/')
    else:
        form = SendMessageForm()
    return render_to_response('inbox/send_message.html', 
                              {'form': form}, 
                              context_instance=RequestContext(request))

@login_required
def delete_message(request, message_id):
    if request.method == 'POST' and request.is_ajax():
        try:
            message = Message.objects.get(id=message_id)
            if request.user == message.sender and request.user == message.receiver:
                message.delete()
            elif request.user == message.sender:
                message.sender_delete()
            else:
                message.receiver_delete()
            return HttpResponse('true')
        except:
            return HttpResponse('false')
    else:
        return HttpResponseRedirect('/inbox/')
        